//
//  UIView+PointConvert.m
//  MyApp
//
//  Created by Don on 2017/8/23.
//
//

#import "UIView+PointConvert.h"
#import <GLKit/GLKit.h>

@implementation UIView (PointConvert)

-(CGFloat)flipY
{
    return -1.0;
}

-(CGPoint)convertToGL:(CGPoint)uiPoint
{
    GLKMatrix4 transform = GLKMatrix4Identity;
    GLKMatrix4 invTransform = GLKMatrix4Invert(transform, NULL);
    
    // Calculate z=0 using -> transform*[0, 0, 0, 1]/w
    float zClip = transform.m[14]/transform.m[15];
    
    CGSize glSize = self.bounds.size;
    GLKVector3 clipCoord = GLKVector3Make(2.0*uiPoint.x/glSize.width - 1.0, 2.0*uiPoint.y/glSize.height - 1.0, zClip);
    
    clipCoord.y *= self.flipY;
    
    GLKVector3 glCoord = GLKMatrix4MultiplyAndProjectVector3(invTransform, clipCoord);
    return CGPointMake(glCoord.x, glCoord.y);
}

-(CGPoint)convertToUI:(CGPoint)glPoint
{
    GLKMatrix4 transform = GLKMatrix4Identity;
    
    GLKVector3 clipCoord = GLKMatrix4MultiplyAndProjectVector3(transform, GLKVector3Make(glPoint.x, glPoint.y, 0.0));
    
    CGSize glSize = self.bounds.size;
    return CGPointMake(glSize.width*(clipCoord.v[0]*0.5 + 0.5), glSize.height*(self.flipY*clipCoord.v[1]*0.5 + 0.5));
}
@end
